<?php
namespace app\common\logic;

use think\Model;
use think\Page;
use think\facade\Db;

/**
 * 分类逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class UsersLogic
{
    protected $user_id=0;

    /**
     * 设置用户ID
     * @param $user_id
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * 网体
     */
    public function getNet(){
        $ary = ['tj'=>'推荐网'];
        return $ary;
    }
    /**
     * 获取登录方式
     */
    public function getLoginMethod(){
        $str ='请输入用户名';//默认
        $method = ['username'];
        //获取登录方式
        $login_method = tpCache('userdata.login_method');
        if($login_method){
            $method = $login_method;
            if(in_array('username',$method) && in_array('mobile',$method)){
                $str = '请输入用户名或手机号';
            }elseif(in_array('mobile',$method)){
                $str = '请输入手机号';
            }
        }
        return ['str'=>$str,'method'=>$method];
    }

    /**
     * 获取用户名
     */
    public function getUsername($id){
        return 'sy000'.$id;
    }


    /**
     * 获取第三方登录的用户
     * @param $openid
     * @param $unionid
     * @param $oauth
     * @param $oauth_child
     * @return array
     */
    private function getThirdUser($data)
    {
        $user = [];
        $thirdUser = Db::name('oauth_users')->where(['openid' => $data['openid'], 'oauth' => $data['oauth']])->find();
        if (!$thirdUser) {
            if ($data['unionid']) {
                $thirdUser = Db::name('oauth_users')->where(['unionid' => $data['unionid']])->find();
                if ($thirdUser) {
                    $data['user_id'] = $thirdUser['user_id'];
                    Db::name('oauth_users')->insert($data);//补充其他第三方登录方式
                }
            }
        }

        if ($thirdUser) {
            $user = Db::name('users')->where('user_id', $thirdUser['user_id'])->find();
            if (!$user) {
                Db::name('oauth_users')->where(['openid' => $data['openid'], 'oauth' => $data['oauth']])->delete();//删除残留数据
            }
        }
        return $user;
    }

    /*
     * 第三方登录: (第一种方式:第三方账号直接创建账号, 不需要额外绑定账号)
     */
    public function thirdLogin($data = array())
    {
        if (!$data['openid'] || !$data['oauth']) {
            return array('status' => -1, 'msg' => '参数有误', 'result' => 'aaa');
        }
        $user2 = session('user');
        if (!empty($user2)) {
            $r = $this->oauth_bind($data);//绑定账号
            if ($r) {
                return array('status' => 1, 'msg' => '绑定成功', 'result' => $user2);
            } else {
                return array('status' => -1, 'msg' => '您的' . $data['oauth'] . '账号已经绑定过账号', 'bind_status' => 0);
            }
        }

        $data['push_id'] && $map['push_id'] = $data['push_id'];
        $map['token'] = md5(time() . mt_rand(1, 999999999));
        $map['last_login'] = time();

        $user = $this->getThirdUser($data);
        if(!$user){
            //账户不存在 注册一个
            $map['password'] = '';
            $map['openid'] = $data['openid'];
            $map['nickname'] = $data['nickname'];
            $map['reg_time'] = time();
            $map['oauth'] = $data['oauth'];
            $map['head_pic'] = !empty($data['head_pic']) ? $data['head_pic'] : '/public/images/icon_goods_thumb_empty_300.png';
            $map['sex'] = $data['sex'] === null ? 0 :  $data['sex'];
            $map['first_leader'] = cookie('first_leader'); // 推荐人id
            if($_GET['first_leader'])
                $map['first_leader'] = $_GET['first_leader']; // 微信授权登录返回时 get 带着参数的

            // 如果找到他老爸还要找他爷爷他祖父等
            if ($map['first_leader']) {
                $first_leader = Db::name('users')->where("user_id = {$map['first_leader']}")->find();
                $map['second_leader'] = $first_leader['first_leader']; //  第一级推荐人
                $map['third_leader'] = $first_leader['second_leader']; // 第二级推荐人
                //他上线分销的下线人数要加1
                Db::name('users')->where(array('user_id' => $map['first_leader']))->setInc('underling_number');
                Db::name('users')->where(array('user_id' => $map['second_leader']))->setInc('underling_number');
                Db::name('users')->where(array('user_id' => $map['third_leader']))->setInc('underling_number');
            } else {
                $map['first_leader'] = 0;
            }
            // 成为分销商条件
            $distribut_condition = tpCache('distribut.condition');
            if($distribut_condition == 0){    // 直接成为分销商, 每个人都可以做分销
                $map['is_distribut']  = 1;
            }
            $row_id = Db::name('users')->add($map);
            $user = Db::name('users')->where(array('user_id'=>$row_id))->find();

            if (!isset($data['oauth_child'])) {
                $data['oauth_child'] = '';
            }

            //不存在则创建个第三方账号
            $data['user_id'] = $user['user_id'];
            $user_level =Db::name('user_level')->where('amount = 0')->find(); //折扣
            $data['discount'] = !empty($user_level) ? $user_level['discount']/100 : 1;  //新注册的会员都不打折
            Db::name('OauthUsers')->save($data);

        } else {
            Db::name('users')->where('user_id', $user['user_id'])->save($map);
            $user['token'] = $map['token'];
            $user['last_login'] = $map['last_login'];
        }

        return array('status'=>1,'msg'=>'登陆成功','result'=>$user);
    }

    /*
     * 第三方登录(第二种方式:第三方账号登录必须绑定账号)
     */
    public function thirdLogin_new($data = array())
    {
        if((empty($data['openid']) && empty($data['unionid'])) || empty($data['oauth'])){
            return ['status' => -1, 'msg' => '参数错误, openid,unionid或oauth为空','result'=>''];
        }

        $user = $this->getThirdUser($data);
        if( ! $user){
            return ['status' => -1, 'msg' => '请绑定账号' , 'result'=>'100'];
        }

        $data['push_id'] && $map['push_id'] = $data['push_id'];
        $map['token'] = md5(time() . mt_rand(1, 999999999));
        $map['last_login'] = time();

        Db::name('users')->where(array('user_id' => $user['user_id']))->save($map);
        //重新加载一次用户信息
        $user = Db::name('users')->where(array('user_id' => $user['user_id']))->find();

        return array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
    }


    /*
     * 获取当前登录用户信息
     */
    public function get_info($user_id)
    {
        $user = Db::name('users')->where('user_id', $user_id)->find();
        $user_wallet = Db::name('Wallet')->where('user_id',$user_id)->find();
        $level_name = Db::name('user_level')->where("rank", $user['level'])->field('level_name,describe')->find();
        $user['level_name'] = $level_name['level_name'];
        $user['level_name_user'] = $level_name['describe'];
        if($user && $user_wallet){
            return array_merge($user,$user_wallet);
        }
        return '';
    }


    /*
     * 获取最近一笔订单
     */
    public function get_last_order($user_id){
        $last_order = M('order')->where("user_id", $user_id)->order('order_id DESC')->find();
        return $last_order;
    }


    /**
     * 获取商品收藏列表
     * @param $user_id
     * @return mixed
     */
    public function get_goods_collect($user_id){
        $count = Db::name('goods_collect')->where('user_id', $user_id)->count();
        $page = new Page($count,10);
        $show = $page->show();
        //获取我的收藏列表
        $result = M('goods_collect')->alias('c')
            ->field('c.collect_id,c.add_time,g.goods_id,g.leixing_id,g.goods_name,g.shop_price,g.is_on_sale,g.store_count,g.cat_id')
            ->join('goods g','g.goods_id = c.goods_id','INNER')
            ->where("c.user_id = $user_id")
            ->limit($page->firstRow,$page->listRows)
            ->select();
        $return['status'] = 1;
        $return['msg'] = '获取成功';
        $return['result'] = $result;
        $return['show'] = $show;
        return $return;
    }

    /**
     * 获取评论列表
     * @param $user_id 用户id
     * @param $status  状态 0 未评论 1 已评论 2全部
     * @return mixed
     */
    public function get_comment($user_id,$status=2){
        if($status == 1){
            //已评论
            $commented_count = Db::name('comment')
                ->alias('c')
                ->join('__ORDER_GOODS__ g','c.goods_id = g.goods_id and c.order_id = g.order_id', 'inner')
                ->where('c.user_id',$user_id)
                ->count();
            $page = new Page($commented_count,10);
            $comment_list = Db::name('comment')
                ->alias('c')
                ->field('c.*,g.*,(select order_sn from  __PREFIX__order where order_id = c.order_id ) as order_sn')
                ->join('__ORDER_GOODS__ g','c.goods_id = g.goods_id and c.order_id = g.order_id', 'inner')
                ->where('c.user_id',$user_id)
                ->order('c.add_time desc')
                ->limit($page->firstRow,$page->listRows)
                ->select();
        }else{
            $comment_where = ['o.user_id'=>$user_id,'og.is_send'=>1,'o.order_status'=>['in',[2,4]]];
            if($status == 0){
                $comment_where['og.is_comment'] = 0;
                $comment_where['o.order_status'] = 2;
            }
            $comment_count = Db::name('order_goods')->alias('og')->join('__ORDER__ o','o.order_id = og.order_id','left')->where($comment_where)->count();
            $page = new Page($comment_count,10);
            $comment_list = Db::name('order_goods')
                ->alias('og')
                ->join('__ORDER__ o','o.order_id = og.order_id','left')
                ->where($comment_where)
                ->order('o.order_id desc')
                ->limit($page->firstRow,$page->listRows)
                ->select();
        }
        $show = $page->show();
        if($comment_list){
            $return['result'] = $comment_list;
            $return['show'] = $show; //分页
            return $return;
        }else{
            return array();
        }
    }



    /**
     * 地址添加/编辑
     * @param $user_id 用户id
     * @param $user_id 地址id(编辑时需传入)
     * @return array
     */
    public function add_address($user_id,$address_id=0,$data){
        $post = $data;
        if($address_id == 0)
        {
            $c = Db::name('UserAddress')->where("user_id", $user_id)->count();
            if($c >= 20)
                return array('status'=>-1,'msg'=>'最多只能添加20个收货地址','result'=>'');
        }

        //检查手机格式
        if($post['consignee'] == '')
            return array('status'=>-1,'msg'=>'收货人不能为空','result'=>'');
        if (!($post['province'] > 0)|| !($post['city']>0) || !($post['district']>0))
            return array('status'=>-1,'msg'=>'所在地区不能为空','result'=>'');
        if(!$post['address'])
            return array('status'=>-1,'msg'=>'地址不能为空','result'=>'');
        if(!check_mobile($post['mobile']))
            return array('status'=>-1,'msg'=>'手机号码格式有误','result'=>'');

        //编辑模式
        if($address_id > 0){

            $address = Db::name('user_address')->where(array('address_id'=>$address_id,'user_id'=> $user_id))->find();
            if($post['is_default'] == 1 && $address['is_default'] != 1)
                Db::name('user_address')->where(array('user_id'=>$user_id))->update(array('is_default'=>0));
            $row = Db::name('user_address')->where(array('address_id'=>$address_id,'user_id'=> $user_id))->update($post);
            if($row !== false){
                return array('status'=>1,'msg'=>'编辑成功','result'=>$address_id);
            }else{
                return array('status'=>-1,'msg'=>'操作完成','result'=>$address_id);
            }

        }
        //添加模式
        $post['user_id'] = $user_id;

        // 如果目前只有一个收货地址则改为默认收货地址
        $c = Db::name('user_address')->where("user_id", $post['user_id'])->count();
        if($c == 0)  {
            $post['is_default'] = 1;
        }else{
            $post['is_default'] = 0;
        }
        unset($post['type']);
        unset($post['addressid']);
        $address_id = Db::name('user_address')->insert($post);
        //如果设为默认地址
        $insert_id = DB::name('user_address')->getLastInsID();
        $map['user_id'] = $user_id;
        $map['address_id'] = array('neq',$insert_id);

        if($post['is_default'] == 1)
            Db::name('user_address')->where($map)->update(array('is_default'=>0));
        if(!$address_id)
            return array('status'=>-1,'msg'=>'添加失败','result'=>'');


        return array('status'=>1,'msg'=>'添加成功','result'=>$address_id);
    }


    /**
     * 设置默认收货地址
     * @param $user_id
     * @param $address_id
     */
    public function set_default($user_id,$address_id){
        M('user_address')->where(array('user_id'=>$user_id))->save(array('is_default'=>0)); //改变以前的默认地址地址状态
        $row = M('user_address')->where(array('user_id'=>$user_id,'address_id'=>$address_id))->save(array('is_default'=>1));
        if(!$row)
            return false;
        return true;
    }

    /**
     * @time 2016/09/01
     * 设置用户系统消息已读
     */
    public function setSysMessageForRead()
    {
        $user_info = session('user');
        if (!empty($user_info['user_id'])) {
            $data['status'] = 1;
            M('user_message')->where(array('user_id' => $user_info['user_id'], 'category' => 0))->save($data);
        }
    }

    /**
     * 设置用户消息已读
     * @param int $category 0:系统消息|1：活动消息
     * @param $msg_id
     * @throws \think\Exception
     */
    public function setMessageForRead($category = 0,$msg_id)
    {
        $user_info = session('user');
        if (!empty($user_info['user_id'])) {
            $data['status'] = 1;
            $set_where['user_id'] = $user_info['user_id'];
            $set_where['category'] = $category;
            if($msg_id){
                $set_where['message_id'] = $msg_id;
            }
            $updat_meg_res = Db::name('user_message')->where($set_where)->update($data);
            if ($updat_meg_res){
                return ['status'=>1,'msg'=>'操作成功'];
            }
        }
        return ['status'=>-1,'msg'=>'操失败'];
    }

    /**
     * 获取访问记录
     * @param type $user_id
     * @param type $p
     * @return type
     */
    public function getVisitLog($user_id, $p = 1)
    {
        $visit = M('goods_visit')->alias('v')
            ->field('v.visit_id, v.goods_id, v.visittime, g.goods_name, g.shop_price, g.cat_id')
            ->join('__GOODS__ g', 'v.goods_id=g.goods_id')
            ->where('v.user_id', $user_id)
            ->order('v.visittime desc')
            ->page($p, 20)
            ->select();

        /* 浏览记录按日期分组 */
        $curyear = date('Y');
        $visit_list = [];
        foreach ($visit as $v) {
            if ($curyear == date('Y', $v['visittime'])) {
                $date = date('m月d日', $v['visittime']);
            } else {
                $date = date('Y年m月d日', $v['visittime']);
            }
            $visit_list[$date][] = $v;
        }

        return $visit_list;
    }


    public function loginSuccess($user){

        //var_dump($user);exit;
        if(empty($user['user_id'])){
            dump($user['user_id']);exit;
        }
        Db::name('users')->where('user_id',$user['user_id'])->update(['last_login'=>time(),'last_ip'=>request()->ip()]);
        $user['login_time'] = time();
        $ip = request()->ip();
        $user['ip'] = $ip;
        $token = base64_encode(json_encode($user));
        return $token;
    }

    public function createuser($mobile='',$password='123456',$intro,$username=''){
        if(!$username){
            $username = getUsername();
        }else{
            $prefix = tpCache('userdata.u_prefix');
            $username = $prefix.$username;
        }

        $curtime = getCurTime();
        $data_u = [];
        $data_u['username'] = $username;
        $data_u['password'] = encrypt($password);
        $data_u['last_ip'] = request()->ip();
        $data_u['reg_time'] = $curtime;
        $data_u['jihuo_time'] = $curtime;
        $data_u['jihuo'] = 1;
        $data_u['last_login'] = $curtime;
        $data_u['is_lock'] = 0;
        $data_u['mobile'] = $mobile;
        $data_u['status'] = 1;
        if(!$username) $data_u['username'] = $data_u['mobile'];
        $exit = Db::name('users')->where(array('username'=>$username))->find();
        if($exit){
            return ['status'=>0,'msg'=>'登录账号已存在'];
        }
        $rstjr = [];
        if($intro){
            $rstjr = Db::name('users')->where(array('username'=>$intro))
                ->field('user_id,username,tjstr,depth')->find();//'is_vip'=>1

            if($rstjr){
                $data_u['tjr_id']=$rstjr['user_id'];
                $data_u['tjr_name']=$rstjr['username'];
                $data_u['depth']=$rstjr['depth']+1;
                if($rstjr['tjstr']!='') {
                    $data_u['tjstr']=$rstjr['user_id'].','.$rstjr['tjstr'];
                }else{
                    $data_u['tjstr']=$rstjr['user_id'];
                }
            }
        }else{
            $data_u['tjr_id'] = 0;
            $data_u['tjr_name'] = '';
        }

        $user_id = Db::name('users')->insertGetId($data_u);


        if ($user_id) {
            //插入钱包
            $dataw = ['user_id' => $user_id];
            $rs = Db::name('wallet')->insert($dataw);
            if (!$rs) {
                return [
                    'status' => false,
                    'msg' => '更新钱包失败',
                ];
            }


            if ($rstjr) {
                //更新团队人数
                $rs = Db::name('users')->where(array('user_id' => array('in', $data_u['tjstr'])))->setInc('totalnum', 1);
                if (!$rs) {
                    return [
                        'status' => false,
                        'msg' => '更新团队人数失败',
                    ];
                }
                //更新推荐数量
                $rs = Db::name('users')->where(array('user_id' => $rstjr['user_id']))->setInc('tjnum', 1);
                if (!$rs) {
                    return [
                        'status' => false,
                        'msg' => '更新直推人数失败',
                    ];
                }
            }
        }
        return [
            'status' => true,
            'username' => $username,
            'user_id' => $user_id
        ];
    }

    public function uplv($order){
        $curtime = getCurTime();
        //判断订单金额是否达到升级金额
        $user = Db::name('users')->where(array('user_id' => $order['user_id']))->find();
        $level = $user['level'];
        $user_level = Db::name('user_level')->where('rank',$level)->find();
        $user_up_money = $user_level['up_money']?:0;
        $now_up_money = bcadd($order['total_shop_price'],$user_up_money,2);
        $new_lv = Db::name('user_level')->where(['up_money'=>$now_up_money,'rank'=>['gt',$level]])->find();
        if(!$new_lv){
            return ['status'=>0,'msg'=>'下单金额未达升级条件'];
        }
        if($new_lv && $new_lv['rank']>$user['level']){
            $rs = Db::name('users')->where(['user_id'=>$order['user_id']])->update(['level'=>$new_lv['rank']]);
            if(!$rs){
                return ['status'=>0,'msg'=>'更新会员级别失败'];
            }
            //插入升级记录
            $insert = array();
            $insert['username'] = $user['username'];
            $insert['old'] = $user['level'];
            $insert['new'] = $new_lv['rank'];
            $insert['w_time'] = $curtime;
            $insert['desc'] = "一次性购物金额达到".$order['total_shop_price']."升级";
            $rs = Db::name('level_log')->insert($insert);
            if(!$rs){
                return ['status'=>0,'msg'=>'添加升级记录失败'];
            }
        }
        return ['status'=>1,'msg'=>'升级成功'];
    }
}